package com.hilaver.dzmis.web.servlet.basicinformation;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Blob;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Hibernate;

import com.hilaver.dzmis.Constants;
import com.hilaver.dzmis.basicinfo.BiReference;
import com.hilaver.dzmis.service.impl.BiReferenceServiceImpl;
import com.hilaver.dzmis.util.StringUtils;
import com.hilaver.dzmis.web.servlet.AbstractBaseServlet;

public class BiReferenceServlet extends AbstractBaseServlet {

	private static final long serialVersionUID = -1143659885015307455L;

	private BiReference reference;
	private BiReferenceServiceImpl referenceService;

	public BiReferenceServlet() {
		super();
		this.referenceService = new BiReferenceServiceImpl();
		this.referenceService.setRealFileDir(UPLOAD_TEMP_REAL_DIR);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		try {
			this.referenceService.setLocale((Locale) request.getSession()
					.getAttribute(Constants.SESSION_LOCALE));
			String outputStr = execute(request);
			if (this.action == ACTION_EDIT) {
				response.setContentType(Constants.HTML_RESPONSE_TYPE);
			}
			writer.write(outputStr);
		} catch (Exception e) {
			writer.print(e.getMessage());
			e.printStackTrace();
		}
		writer.close();
	}

	protected String execute(HttpServletRequest request) throws Exception {
		super.setAction(request);
		String rtn = "";
		switch (this.action) {
		case ACTION_GET: // "get one"
			super.setId(request);
			rtn = this.referenceService.get(this.id);
			break;
		case ACTION_GET_WITH_DESCRIPTION:

			break;
		case ACTION_DELETE:
			super.setId(request);
			rtn = this.referenceService.delete(this.id);
			break;
		case ACTION_GET_ALL_PAGINATION_FILTER:
			super.setPaginationParam(request);
			super.setFilterParam(request);
			rtn = this.referenceService.getAllPagination(this.page, this.sort,
					this.dir, super.filters);
			break;
		case ACTION_EDIT:
			this.fillObj(request);
			rtn = this.referenceService.edit(this.reference);
			break;
		}
		return rtn;
	}

	private void fillObj(HttpServletRequest request) throws Exception {
		this.reference = new BiReference();
		if (ServletFileUpload.isMultipartContent(request)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(MAX_UPLOAD_FILE_CACHE);
			factory.setRepository(new File(getServletContext().getRealPath(
					UPLOAD_TEMP_DIR)));
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(MAX_UPLOAD_FILE_SIZE);

			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				String fieldName = item.getFieldName();
				String value;
				if ("id".equals(fieldName)) {
					value = item.getString(Constants.ENCODING);
					if (!StringUtils.isEmpty(value)) {
						this.reference.setId(Integer.parseInt(value));
					} else {
						this.reference.setId(null);
					}
				} else if ("reference".equals(fieldName)) {
					this.reference.setReference(item
							.getString(Constants.ENCODING));
				} else if ("ctMachineType".equals(fieldName)) {
					value = item.getString(Constants.ENCODING);
					this.reference.setCtMachineType(item
							.getString(Constants.ENCODING));
				} else if ("needle".equals(fieldName)) {
					value = item.getString(Constants.ENCODING);
					this.reference.setNeedle(Integer.parseInt(value));
				} else if ("weight".equals(fieldName)) {
					value = item.getString(Constants.ENCODING);
					this.reference.setWeight(Float.parseFloat(value));
				} else if ("front".equals(fieldName)) {
					this.reference.setFront(item.getString(Constants.ENCODING));
				} else if ("back".equals(fieldName)) {
					this.reference.setBack(item.getString(Constants.ENCODING));
				} else if ("sleeves".equals(fieldName)) {
					this.reference.setSleeves(item
							.getString(Constants.ENCODING));
				} else if ("bottomThrum".equals(fieldName)) {
					this.reference.setBottomThrum(item
							.getString(Constants.ENCODING));
				} else if ("sleevesThrum".equals(fieldName)) {
					this.reference.setSleevesThrum(item
							.getString(Constants.ENCODING));
				} else if ("necklineThrum".equals(fieldName)) {
					this.reference.setNecklineThrum(item
							.getString(Constants.ENCODING));
				} else if ("comment".equals(fieldName)) {
					this.reference.setComment(item
							.getString(Constants.ENCODING));
				} else if ("frontPhoto".equals(fieldName)) {
					String frontPhotoName;
					;
					Blob frontPhoto;
					if (item.getSize() > 0) {
						frontPhotoName = System.currentTimeMillis()
								+ StringUtils.getFileExtension(item.getName());
						frontPhoto = Hibernate
								.createBlob(item.getInputStream());
						item.write(new File(UPLOAD_TEMP_REAL_DIR
								+ frontPhotoName));
					} else {
						frontPhotoName = null;
						frontPhoto = null;
					}
					this.reference.setFrontPhoto(frontPhoto);
					this.reference.setFrontPhotoName(frontPhotoName);
				} else if ("backPhoto".equals(fieldName)) {
					String backPhotoName;
					;
					Blob backPhoto;
					if (item.getSize() > 0) {
						backPhotoName = System.currentTimeMillis()
								+ StringUtils.getFileExtension(item.getName());
						backPhoto = Hibernate.createBlob(item.getInputStream());
						item.write(new File(UPLOAD_TEMP_REAL_DIR
								+ backPhotoName));
					} else {
						backPhotoName = null;
						backPhoto = null;
					}
					this.reference.setBackPhoto(backPhoto);
					this.reference.setBackPhotoName(backPhotoName);
				} else if ("otherPhoto".equals(fieldName)) {
					String otherPhotoName;
					;
					Blob otherPhoto;
					if (item.getSize() > 0) {
						otherPhotoName = System.currentTimeMillis()
								+ StringUtils.getFileExtension(item.getName());
						otherPhoto = Hibernate
								.createBlob(item.getInputStream());
						item.write(new File(UPLOAD_TEMP_REAL_DIR
								+ otherPhotoName));
					} else {
						otherPhotoName = null;
						otherPhoto = null;
					}
					this.reference.setOtherPhoto(otherPhoto);
					this.reference.setOtherPhotoName(otherPhotoName);
				}
			}
		}
	}
}